package com.c201801020208.ybl.Login.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.c201801020208.ybl.R;
import com.c201801020208.ybl.Tables.PUser;
import com.c201801020208.ybl.Tool.MD5Util;
import com.facebook.stetho.Stetho;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.BuildConfig;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class Register2Activity extends AppCompatActivity implements View.OnClickListener {
    ImageView imageView;
    ImageView imageView2;
    ImageView imageView3;
    Button button;
    EditText editText1;
    EditText editText2;
    EditText editText3;
    TextView textView;
    private boolean isHideFirst = true;// 输入框密码是否是隐藏的，默认为true


    //usersig签名
    private final static String sig = "eJwtzF0LgjAUxvHvsttCzlnbKKGLLoRFIkiS163NOr3IMBlW9N0z9fL5PfD-sCLdR8E1LGY8AjYfNllXt1TRwPfrpE97O3pPlsUoAIREXKnxcZ2nxvUupeQAMGpLj78pUIhcCZwqdO6jJhwW7yZ0aUfbrE6KWbnJdXUCuGS8VDtdi0Qb88rDMl*z7w9vfzAZ";
    private final static String URL = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=1400451196&identifier=lj&usersig=" + sig + "&random=999999&contenttype=json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register2);
        Stetho.initializeWithDefaults(this);
        x.Ext.init(getApplication());
        x.Ext.setDebug(BuildConfig.DEBUG);// 是否输出debug日志, 开启debug会影响性能.
        x.view().inject(this);//没有用到view注解可以先不用


        //主线程使用网络请求
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        editText1 = findViewById(R.id.editText3);
        editText2 = findViewById(R.id.editText4);
        editText3 = findViewById(R.id.editText5);
        imageView = findViewById(R.id.imageView);
        imageView2 = findViewById(R.id.delete);
        imageView3 = findViewById(R.id.see);
        button = findViewById(R.id.button);
        textView = findViewById(R.id.textView12);

        initListener();


        //注册
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editText1.getText().toString().trim() != "" && editText2.getText().toString().trim() != "" && editText2.getText().toString().trim().equals(editText3.getText().toString().trim())) {
                    PUser user = new PUser();
                    user.setId(1);
                    user.setUsername(editText1.getText().toString().trim());
                    user.setPassword(MD5Util.getMD5Str(editText2.getText().toString().trim()));
                    user.setId(1);
                    user.save(new SaveListener<String>() {
                        @Override
                        public void done(String objectId, BmobException e) {
                            if (e == null) {
                                Toast.makeText(Register2Activity.this, "添加数据成功", Toast.LENGTH_LONG);
                            } else {
                                Toast.makeText(Register2Activity.this, "创建数据失败：" + e.getMessage(), Toast.LENGTH_LONG);
                            }
                        }
                    });
                    try {
                        String tt = "https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2853553659,1775735885&fm=26&gp=0.jpg";
                        imUser(editText1.getText().toString().trim(), tt);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(Register2Activity.this, Login2Activity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });
        //取消
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Register2Activity.this, Login2Activity.class);
                startActivity(intent);
                finish();
            }
        });

    }


    //     * 生成IM用户
//     * username 你要生成的用户名
//     * headurl 你用户的头像路径
    public String imUser(String username, String headurl) throws IOException {
        // TODO Auto-generated method stub
        // 连接服务器
        HttpURLConnection connection = connection(URL);
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        JSONObject obj = new JSONObject();
        try {
            obj.put("Identifier", editText1.getText().toString().trim());
            obj.put("Nick", editText1.getText().toString().trim());
            obj.put("FaceUrl", headurl);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("user", obj.toString());

        // 向腾讯请求传入编码为UTF-8格式的json数据
        out.write(obj.toString().getBytes("UTF-8"));
        out.flush();
        out.close();
        // 获得服务器返回的结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        StringBuffer sb = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        Log.i("user", String.valueOf(sb));
        // 将BufferedReader转换为String 类型，然后进行解析
        String returnString = sb.toString();
        JsonObject jObject = new JsonParser().parse(returnString).getAsJsonObject();
        String ActionStatus = jObject.get("ActionStatus").getAsString();
        Log.i("user", ActionStatus);
        return ActionStatus;
    }

    public static HttpURLConnection connection(String URL) throws IOException {//post连接请求
        java.net.URL url = new URL(URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        connection.connect();
        return connection;
        // TODO Auto-generated method stub
    }


    //设置监听器
    private void initListener() {
        editText1.addTextChangedListener(textWatcher);
        editText3.addTextChangedListener(textWatcher);
        imageView2.setOnClickListener(this);
        imageView3.setOnClickListener(this);
        imageView3.setImageResource(R.drawable.d);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (editText1.getEditableText().length() >= 1) {
                imageView2.setVisibility(View.VISIBLE);
            } else {
                imageView2.setVisibility(View.GONE);
            }

            if (editText3.getEditableText().length() >= 1) {
                if (editText3.getText().toString().equals(editText2.getText().toString())) {
                    textView.setText("密码一致!");
                    textView.setTextColor(Color.parseColor("#00FF00"));
                } else {
                    textView.setText("两次密码不一致!");
                    textView.setTextColor(Color.parseColor("#FF0000"));
                }
            } else {
                textView.setText("");
            }
        }
    };

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.delete:
                editText1.setText("");
                break;
            case R.id.see:
                if (isHideFirst == true) {
                    imageView3.setImageResource(R.drawable.c);
                    //密文
                    HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                    editText2.setTransformationMethod(method1);
                    editText3.setTransformationMethod(method1);
                    isHideFirst = false;
                } else {
                    imageView3.setImageResource(R.drawable.d);
                    //密文
                    TransformationMethod method = PasswordTransformationMethod.getInstance();
                    editText2.setTransformationMethod(method);
                    editText3.setTransformationMethod(method);
                    isHideFirst = true;
                }
                // 光标的位置
                int index = editText2.getText().toString().length();
                editText2.setSelection(index);
                int index2 = editText3.getText().toString().length();
                editText3.setSelection(index2);
                break;
        }

    }
}